// 获取当前题目内容
var currentOption = {
  stxx: [
    {
      xxnr: "&nbsp; 农业农村现代化&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br/>\r",
      xxbh: "A",
    },
    {
      xxnr: "&nbsp; 乡村治理有效&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <br/>\r",
      xxbh: "B",
    },
    {
      xxnr: "&nbsp; 建立健全城乡融合发展的体制机制和政策体系建立健全城乡融合发展的体制机制和政策体系建立健全城乡融合发展的体制机制和政策体系建立健全城乡融合发展的体制机制和政策体系建立健全城乡融合发展的体制机制和政策体系<br/>\r",
      xxbh: "C",
    },
    {
      xxnr: "&nbsp; 农业农村优先发展<br/>\r",
      xxbh: "D",
    },
  ],
  stid: "N1624032510000000304",
  stnr: "<p>实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是实施乡村振兴战略的总目标是（）。<br/>\r</p>",
};
// 获取全部题目
var examquestions = [
  {
    tmlb: [
      {
        bjzt: null,
        yhda: "A",
        yhstid: "N1624032510000000302",
        stlx: "2",
      },
      {
        bjzt: 1,
        yhda: null,
        yhstid: "N1624032510000000303",
        stlx: "2",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000304",
        stlx: "1",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000305",
        stlx: "2",
      },
    ],
    jgid: "N1624032010000000022",
    jgmc: "第一大题",
  },
  {
    tmlb: [
      {
        bjzt: 1,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000270",
        stlx: "3",
      },
      {
        bjzt: null,
        yhda: "123dasaaa",
        yhstid: "N1624032010000000271",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000272",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000273",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000274",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000274",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000274",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000274",
        stlx: "4",
      },
    ],
    jgid: "N1624032010000000021",
    jgmc: "第二大题",
  },
  {
    tmlb: [
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000290",
        stlx: "4",
      },
      {
        bjzt: null,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000291",
        stlx: "4",
      },
      {
        bjzt: 1,
        yhda: "ertergfgdfergerg",
        yhstid: "N1624032010000000292",
        stlx: "4",
      },
    ],
    jgid: "N1624031510000000018",
    jgmc: "第三大题",
  },
  {
    tmlb: [
      {
        bjzt: null,
        yhda: "A",
        yhstid: "N1624032510000000302",
        stlx: "2",
      },
      {
        bjzt: 1,
        yhda: null,
        yhstid: "N1624032510000000303",
        stlx: "2",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000304",
        stlx: "1",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000305",
        stlx: "2",
      },
    ],
    jgid: "N1624032010000000022",
    jgmc: "第一大题",
  },
  {
    tmlb: [
      {
        bjzt: null,
        yhda: "A",
        yhstid: "N1624032510000000302",
        stlx: "2",
      },
      {
        bjzt: 1,
        yhda: null,
        yhstid: "N1624032510000000303",
        stlx: "2",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000304",
        stlx: "1",
      },
      {
        bjzt: null,
        yhda: null,
        yhstid: "N1624032510000000305",
        stlx: "2",
      },
    ],
    jgid: "N1624032010000000022",
    jgmc: "第一大题",
  },
];
// 当前题目内容
var currentSubject = {
  // 字体大小
  size: "normal",
  // 大标题
  topTitle: "",
  // 展示序号
  index: "",
  // 题目标题
  title: "",
  // 题目id
  id: "",
  // 题目选项列表
  option: [],
  // 当前题目答案
  current: "",
};

// 当前选择题目
var currentType = "";
var currentId = "";
// 中间frame
var subjectIframe = $("#subjectIframe");
// 帮助文档标记
var hintFlag = false;

// layui
var layer = layui.layer;
var laytpl = layui.laytpl;
// 获取模板内容
var getTpl = leftBody.innerHTML;
//  渲染视图
var view = document.getElementById("view");

// 初始化题目
getCurrentData();

// 题目列表点击事件
$(document).on("click", ".left-content-body-index", function () {
  saveCurrent();
  currentType = $(this).data("type");
  currentId = $(this).data("id");
  // 获取当前题目内容
  currentSubject.index = $(this).data("index");
  currentSubject.topTitle = $(this).data("title");
  var stid = $(this).data("stid");
  // 初始化题目
  initCurrent(stid, currentId);
  // 修改左侧
  changeLeft();
  // 标记按钮切换状态
  if ($(this).data("sign") == 1) {
    $(".signBtn").hide();
    $(".signedBtn").css("display", "flex");
  } else {
    $(".signedBtn").hide();
    $(".signBtn").css("display", "flex");
  }
});

// 上一题
$(document).on("click", ".lastBtn", function () {
  var lastIndex = 0;
  $(".left-content-body-index").each(function (index, el) {
    if (currentId === $(el).data("id")) {
      lastIndex = index - 1;
    }
  });
  if (lastIndex !== -1) {
    $(".left-content-body-index").each(function (index, el) {
      if (index === lastIndex) {
        $(el).trigger("click");
      }
    });
  } else {
    layer.msg("没有上一题了", { icon: 5 });
  }
});

// 下一题
$(document).on("click", ".nextBtn", function () {
  var nextIndex = 0;
  $(".left-content-body-index").each(function (index, el) {
    if (currentId === $(el).data("id")) {
      nextIndex = index + 1;
    }
  });
  if (nextIndex !== $(".left-content-body-index").length) {
    $(".left-content-body-index").each(function (index, el) {
      if (index === nextIndex) {
        $(el).trigger("click");
      }
    });
  } else {
    layer.msg("没有下一题了", { icon: 5 });
  }
});

// 标记/取消标记 本题
$(".signBtn").click(function () {
  $(".signBtn").hide();
  $(".signedBtn").css("display", "flex");

  signBtnClick(true);
});
$(".signedBtn").click(function () {
  $(".signedBtn").hide();
  $(".signBtn").css("display", "flex");
  signBtnClick(false);
});

// 帮助
$(".action-bar-hint").click(function () {
  if (hintFlag) {
    hintFlag = false;
    $(".action-bar-hint-content").hide();
    $(".action-bar-hint-img").attr("src", "./imgs/hint.png");
  } else {
    hintFlag = true;
    $(".action-bar-hint-content").show();
    $(".action-bar-hint-img").attr("src", "./imgs/hint-blue.png");
  }
});

// 修改字体大小
$(".small").click(function () {
  currentSubject.size = "small";
  subjectIframe[0].contentWindow.changeSize("small");
  $(".action-bar-fontSize-progress-btn").css("left", "13.5%");
  $(".small ").css("color", "#0d61a2");
  $(".normal ").css("color", "#999999");
  $(".larger ").css("color", "#999999");
  // document.getElementById("subjectIframe").contentWindow.location.reload();
});
$(".normal").click(function () {
  currentSubject.size = "normal";
  subjectIframe[0].contentWindow.changeSize("normal");
  $(".action-bar-fontSize-progress-btn").css("left", "44%");
  $(".small ").css("color", "#999999");
  $(".normal ").css("color", "#0d61a2");
  $(".larger ").css("color", "#999999");
  // document.getElementById("subjectIframe").contentWindow.location.reload();
});
$(".larger").click(function () {
  currentSubject.size = "larger";
  subjectIframe[0].contentWindow.changeSize("larger");
  $(".action-bar-fontSize-progress-btn").css("left", "77%");
  $(".small ").css("color", "#999999");
  $(".normal ").css("color", "#999999");
  $(".larger ").css("color", "#0d61a2");
  // document.getElementById("subjectIframe").contentWindow.location.reload();
});

// 交卷
$(".main-header .header-right .button").click(function () {
  saveCurrent();
  layer.open({
    title: "提示",
    content: "确定要交卷吗?",
    btn: ["确定", "取消"],
    yes: function (index, layero) {
      var formData = new FormData();
      formData.append("pcid", "1");
      $.ajax({
        method: "post",
        url: "http://192.168.200.97:8080/ncms/exam.do?method=saveUserExamItemSubmit",
        data: formData,
        processData: false,
        contentType: false,
        success: function (responseText) {
          //按钮【按钮一】的回调
          window.location.replace("./end.html");
        },
      });
    },
    btn2: function (index, layero) {
      //按钮【按钮二】的回调
      //return false 开启该代码可禁止点击该按钮关闭
    },
  });
});
// 获取题目信息
function getCurrentData() {
  laytpl(getTpl).render(examquestions, function (html) {
    view.innerHTML = html;
    // 默认第一题
    $(".left-content-body-index").each(function (index, el) {
      if (index === 0) {
        $(el).trigger("click");
      }
    });
  });
  // 初始化执行函数
  initProgress();
  initTime();
  return;
  if (sessionStorage.getItem("examineeinfo")) {
    examquestions = JSON.parse(sessionStorage.getItem("examquestions"));
    var examineeinfo = JSON.parse(sessionStorage.getItem("examineeinfo"));

    $(".info-name").text(examineeinfo.xm);
    $(".info-date").text(examineeinfo.dtksrq);
    $(".info-img").attr(
      "src",
      "http://192.168.200.97:8080/ncms/userrg.do?method=downloadRegisterPhoto&pcid=1",
    );
    $(".info-date-time").text(examineeinfo.kssj + "~" + examineeinfo.jssj);

    laytpl(getTpl).render(examquestions, function (html) {
      view.innerHTML = html;
    });
    window.onload = function () {
      // 默认第一题
      $(".left-content-body-index").each(function (index, el) {
        if (index === 0) {
          $(el).trigger("click");
        }
      });
    };
    // 初始化执行函数
    initProgress();
    initTime();
  } else {
    var formData = new FormData();
    formData.append("pcid", "1");
    $.ajax({
      method: "post",
      url: "http://192.168.200.97:8080/ncms/exam.do?method=queryExamQuestions",
      data: formData,
      processData: false,
      contentType: false,
      success: function (responseText) {
        var data = JSON.parse(responseText);
        if (data.wcks == 1) {
          return window.location.replace("./end.html");
        }
        if (data.msg) {
          return layer.confirm("提示", {
            btn: "确定",
            title: data.msg,
            btnAlign: "c",
          });
        }
        examquestions = data.examquestions;
        var examineeinfo = data.examineeinfo;
        sessionStorage.setItem("examquestions", JSON.stringify(examquestions));
        sessionStorage.setItem("examineeinfo", JSON.stringify(examineeinfo));
        $(".info-name").text(examineeinfo.xm);
        $(".info-date").text(examineeinfo.dtksrq);
        $(".info-img").attr(
          "src",
          "http://192.168.200.97:8080/ncms/userrg.do?method=downloadRegisterPhoto&pcid=1",
        );
        $(".info-date-time").text(examineeinfo.kssj + "~" + examineeinfo.jssj);
        laytpl(getTpl).render(examquestions, function (html) {
          view.innerHTML = html;
          // 默认第一题
          $(".left-content-body-index").each(function (index, el) {
            if (index === 0) {
              $(el).trigger("click");
            }
          });
        });
        // 初始化执行函数
        initProgress();
        initTime();
      },
      complete: function (xhr, status) {},
    });
  }
}
// 获取当前题目信息
function getCurrentTopic(id) {
  ajax({
    url: "/test",
    type: "get",
    data: {
      id: id,
    },
    success: function (res) {},
    error: function () {},
  });
}
// 修改左侧列表状态
function changeLeft() {
  $(".left-content-body-index").each(function (index, el) {
    // 修改标记状态
    if ($(el).data("sign") == 1) {
      $(el).addClass("left-content-body-index-sign");
    } else {
      $(el).removeClass("left-content-body-index-sign");
    }
    // 答题状态
    if ($(el).data("answering").length) {
      $(el).addClass("left-content-body-index-answered");
    } else {
      $(el).removeClass("left-content-body-index-answered");
    }
    // 选中状态
    $(el).removeClass("left-content-body-index-checked");
    if (currentId == $(el).data("id")) {
      $(el).addClass("left-content-body-index-checked");
    }
  });
}
// 初始化当前题目
function initCurrent(stid, yhstid) {
  currentSubject.title = currentOption.stnr;
  currentSubject.id = currentOption.stid;
  currentSubject.option = currentOption.stxx;
  // 修改子页面
  switch (currentType) {
    // 单选
    case 1:
      subjectIframe.attr("src", "./pages/select.html");
      break;
    // 多选
    case 2:
      subjectIframe.attr("src", "./pages/multiple.html");
      break;
    // 判断
    case 3:
      subjectIframe.attr("src", "./pages/judge.html");
      break;
    // 简答
    case 4:
      subjectIframe.attr("src", "./pages/short.html");
      break;
  }

  return;
  var formData = new FormData();
  formData.append("pcid", "1");
  formData.append("stid", stid);
  formData.append("yhstid", yhstid);

  // 获取当前题目数据
  $.ajax({
    method: "post",
    url: "http://192.168.200.97:8080/ncms/exam.do?method=queryTestQuestionInfo",
    data: formData,
    processData: false,
    contentType: false,
    success: function (responseText) {
      var data = JSON.parse(responseText);

      // 修改子页面
      switch (currentType) {
        // 单选
        case 1:
          subjectIframe.attr("src", "./pages/select.html");
          break;
        // 多选
        case 2:
          subjectIframe.attr("src", "./pages/multiple.html");
          break;
        // 判断
        case 3:
          subjectIframe.attr("src", "./pages/judge.html");
          break;
        // 简答
        case 4:
          subjectIframe.attr("src", "./pages/short.html");
          break;
      }
    },
    complete: function (xhr, status) {},
  });
}
// 标记题目函数
function signBtnClick(flag) {
  if (flag) {
    $(".left-content-body-index").each(function (index, el) {
      if (currentId == $(el).data("id")) {
        $(el).data("sign", "1");
      }
    });
  } else {
    $(".left-content-body-index").each(function (index, el) {
      if (currentId == $(el).data("id")) {
        $(el).data("sign", "0");
      }
    });
  }
  // 修改数据
  examquestions = examquestions.map(function (item) {
    item.tmlb = item.tmlb.map(function (item1) {
      if (item1.yhstid === currentId) {
        if (flag) {
          item1.bjzt = "1";
        } else {
          item1.bjzt = "0";
        }
      }
      return item1;
    });
    return item;
  });
  sessionStorage.setItem("examquestions", JSON.stringify(examquestions));
  saveCurrent();
  changeLeft();
}
// 获取当前内容
function getCurrentSubject() {
  return currentSubject;
}
// 初始化进度条
function initProgress() {
  var allItem = 0;
  var answeredItem = 0;
  examquestions.forEach(function (item) {
    item.tmlb.forEach(function (item1) {
      if (item1.yhda) {
        answeredItem++;
      }
      allItem++;
    });
  });

  $(".left-progress-bar").css("width", (answeredItem / allItem) * 100 + "%");
  var content =
    "答题进度：" +
    '<span style="color:#42ba7a">' +
    answeredItem +
    "</span>" +
    "/" +
    allItem;
  $(".left-rectangle-text").html(content);
}
// 更改iframe 高度
function autoIframeHeight() {
  // 获取iframe的document对象
  var iframeDocument =
    document.getElementById("subjectIframe").contentDocument ||
    document.getElementById("subjectIframe").contentWindow.document;

  // 获取div的高度
  var divHeight = iframeDocument
    .getElementById("maniBody")
    .getBoundingClientRect().height;

  // 输出div的高度
  document.getElementById("subjectIframe").height = divHeight;
}
// 修改答案
function changeData(data) {
  $(".left-content-body-index").each(function (index, el) {
    // 答题状态
    if ($(el).data("id") === currentId) {
      $(el).data("answering", data);
    }
  });
  // 修改数据
  examquestions = examquestions.map(function (item) {
    item.tmlb = item.tmlb.map(function (item1) {
      if (item1.yhstid === currentId) {
        item1.yhda = data;
      }
      return item1;
    });
    return item;
  });
  sessionStorage.setItem("examquestions", JSON.stringify(examquestions));
  saveCurrent();
  initProgress();
  changeLeft();
}
// 获取当前题目答案
function getCurrentAnswer() {
  var data = "";
  $(".left-content-body-index").each(function (index, el) {
    // 答题状态
    if ($(el).data("id") === currentId) {
      data = $(el).data("answering");
    }
  });
  return data;
}

// 保存当前数据
function saveCurrent() {
  examquestions.forEach(function (item) {
    item.tmlb.forEach(function (item1) {
      if (item1.yhstid === currentId) {
        // 请求修改数据
        var formData = new FormData();
        formData.append("pcid", "1");
        formData.append("yhstid", item1.yhstid);
        formData.append("yhda", item1.yhda);
        formData.append("bjzt", item1.bjzt);
        $.ajax({
          method: "post",
          url: "http://192.168.200.97:8080/ncms/exam.do?method=saveUserExamItemAnswer",
          data: formData,
          processData: false,
          contentType: false,
          success: function (responseText) {},
        });
      }
    });
  });
}
// $(document).ready();
function initTime() {
  var formData = new FormData();
  formData.append("pcid", "1");
  $.ajax({
    method: "post",
    url: "http://192.168.200.97:8080/ncms/exam.do?method=queryRemainingExamTime",
    data: formData,
    processData: false,
    contentType: false,
    success: function (responseText) {
      var data = JSON.parse(responseText);
      var totalSeconds = data.remainingtime; // 假设我们倒计时1小时 (3600秒)

      function updateTimer() {
        var hours = Math.floor(totalSeconds / 3600);
        var minutes = Math.floor((totalSeconds % 3600) / 60);
        var seconds = totalSeconds % 60;

        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        $("#timer").text(hours + ":" + minutes + ":" + seconds);

        if (totalSeconds > 0) {
          totalSeconds--;
        } else {
          clearInterval(interval);
        }
      }

      updateTimer(); // 初始更新
      var interval = setInterval(updateTimer, 1000); // 每秒更新一次
    },
  });
}
// JavaScript代码

// 离开此页函数
// window.addEventListener("beforeunload", function (event) {
//   // 在这里执行你需要的代码
//   // 例如发送AJAX请求，保存用户数据等等
//   event.preventDefault();
//   event.returnValue = "确定离开此页吗？";
// });

// introJs
// 绑定标签元素的选择器数组
let yindaoList = [
  {
    element: document.querySelector(".centre"),
    title: "温馨提示：", // 标题
    intro:
      "答题区域：展示当前正在作答的题目信息，考生可在此区域内对题目进行作答。", // 内容
    tooltipClass: "centreTip",
    position: "left",
  },
  {
    element: document.querySelector(".info"),
    title: "温馨提示：", // 标题
    intro: "考生信息展示区域：请仔细核对考生照片以及考生姓名等信息是否正确。", // 内容
    tooltipClass: "infoTip",
    position: "left",
  },
  {
    element: document.querySelector(".left-rectangle"),
    title: "温馨提示：", // 标题
    intro: "答题进度区域：此处展示您当前的答题进度。", // 内容
    tooltipClass: "leftRectangle",
    position: "right",
  },
  {
    element: document.querySelector(".left-body"),
    title: "温馨提示：", // 标题
    intro: "题目列表：展示当前考试所有题目，点击题号可跳转到指定题目进行作答。", // 内容
    tooltipClass: "leftBody",
    position: "right",
  },

  {
    element: document.querySelector("#savebtn"), // 定位到相应的元素位置，如果不设置element，则默认展示在屏幕中央
    title: "温馨提示：", // 标题
    intro:
      "答题完成后，需要点击 <span style='color:#42ba7a'> “交卷” </span> 按钮进行交卷，结束当前考试。",
    tooltipClass: "savebtnTip",
  },
];

introJs()
  .setOptions({
    steps: yindaoList, //上面声明的数组
    prevLabel: "上一步",
    nextLabel: "下一步",
    doneLabel: "完成", // 完成按钮的文字
    // skipLabel: "跳过",
    tooltipClass: "intro-tooltip" /* 引导说明文本框的样式 */,
    exitOnEsc: true /* 是否使用键盘Esc退出 */,
    exitOnOverlayClick: false /* 是否允许点击空白处退出 */,
    keyboardNavigation: true /* 是否允许键盘来操作 */,
    showBullets: false /* 是否显示小圆点 */,
    showStepNumbers: true /* 是否显示数字 */,
    stepNumbersOfLabel: "/",
    showProgress: false /* 是否显示进度条 */,
    scrollToElement: true /* 是否滑动到高亮的区域 */,
    overlayOpacity: 0.65, // 遮罩层的透明度 0-1之间
    positionPrecedence: [
      "bottom",
      "top",
      "right",
      "left",
    ] /* 当位置选择自动的时候，位置排列的优先级 */,
    disableInteraction: true /* 是否禁止与元素的相互关联 */,
    hidePrev: true /* 是否在第一步隐藏上一步 */,
    hideNext: false /* 是否在最后一步隐藏下一步 */,
  })
  // 点击结束按钮后执行的事件
  .oncomplete(() => {})
  // 点击跳过按钮后执行的事件
  .onexit(() => {})
  // 确认完毕之后执行的事件
  .onbeforeexit(() => {
    // localStorage.setItem("introValue", "true");
  })
  .start();
